<?php
/**
 * 发送短信验证码 - 使用腾讯云SMS API
 */

session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
header('Content-Type: application/json');

// 获取POST数据
$input = file_get_contents('php://input');
$data = json_decode($input, true);

if (!isset($data['phone']) || empty($data['phone'])) {
    echo json_encode(['success' => false, 'message' => '请输入手机号']);
    exit;
}

$phone = $data['phone'];

// 验证手机号格式
if (!preg_match('/^1[3-9]\d{9}$/', $phone)) {
    echo json_encode(['success' => false, 'message' => '手机号格式不正确']);
    exit;
}

// 读取配置
$config = include __DIR__ . '/../../config.php';
$smsConfig = $config['plugins']['sms'] ?? [];

if (empty($smsConfig['enabled']) || !$smsConfig['enabled']) {
    echo json_encode(['success' => false, 'message' => '短信服务未启用']);
    exit;
}

// 验证配置完整性
$requiredFields = ['secret_id', 'secret_key', 'sdk_app_id', 'sign_name', 'template_id'];
foreach ($requiredFields as $field) {
    if (empty($smsConfig[$field])) {
        echo json_encode(['success' => false, 'message' => '短信服务配置不完整，请检查：' . $field]);
        exit;
    }
}

// 生成6位验证码
$code = str_pad(mt_rand(0, 999999), 6, '0', STR_PAD_LEFT);

// 保存验证码到session（5分钟有效）
$_SESSION['sms_code'] = $code;
$_SESSION['sms_phone'] = $phone;
$_SESSION['sms_time'] = time();

try {
    // 调用腾讯云SMS API发送短信
    $result = sendTencentSms(
        $smsConfig['secret_id'],
        $smsConfig['secret_key'],
        $smsConfig['sdk_app_id'],
        $smsConfig['sign_name'],
        $smsConfig['template_id'],
        $phone,
        [$code, '5'], // 验证码和有效期（分钟）
        $smsConfig['region'] ?? 'ap-guangzhou'
    );
    
    if ($result['success']) {
        echo json_encode(['success' => true, 'message' => '验证码已发送']);
    } else {
        echo json_encode(['success' => false, 'message' => '发送失败：' . $result['message']]);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => '发送失败：' . $e->getMessage()]);
}

/**
 * 发送腾讯云短信
 */
function sendTencentSms($secretId, $secretKey, $sdkAppId, $signName, $templateId, $phone, $templateParams, $region) {
    $endpoint = 'sms.tencentcloudapi.com';
    $service = 'sms';
    $version = '2021-01-11';
    $action = 'SendSms';
    $timestamp = time();
    $date = gmdate('Y-m-d', $timestamp);
    
    // 请求参数
    $params = [
        'PhoneNumberSet' => ['+86' . $phone],
        'SmsSdkAppId' => $sdkAppId,
        'SignName' => $signName,
        'TemplateId' => $templateId,
        'TemplateParamSet' => $templateParams
    ];
    
    $payload = json_encode($params);
    
    // 构造签名
    $algorithm = 'TC3-HMAC-SHA256';
    $canonicalRequest = "POST\n/\n\ncontent-type:application/json\nhost:" . $endpoint . "\n\ncontent-type;host\n" . hash('sha256', $payload);
    $credentialScope = $date . '/' . $service . '/tc3_request';
    $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
    $stringToSign = $algorithm . "\n" . $timestamp . "\n" . $credentialScope . "\n" . $hashedCanonicalRequest;
    
    $secretDate = hash_hmac('sha256', $date, 'TC3' . $secretKey, true);
    $secretService = hash_hmac('sha256', $service, $secretDate, true);
    $secretSigning = hash_hmac('sha256', 'tc3_request', $secretService, true);
    $signature = hash_hmac('sha256', $stringToSign, $secretSigning);
    
    $authorization = $algorithm . ' Credential=' . $secretId . '/' . $credentialScope . ', SignedHeaders=content-type;host, Signature=' . $signature;
    
    // 发送请求
    $headers = [
        'Authorization: ' . $authorization,
        'Content-Type: application/json',
        'Host: ' . $endpoint,
        'X-TC-Action: ' . $action,
        'X-TC-Timestamp: ' . $timestamp,
        'X-TC-Version: ' . $version,
        'X-TC-Region: ' . $region
    ];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://' . $endpoint);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    if ($error) {
        return ['success' => false, 'message' => 'CURL错误：' . $error];
    }
    
    $result = json_decode($response, true);
    
    if ($httpCode !== 200) {
        return ['success' => false, 'message' => 'HTTP错误：' . $httpCode];
    }
    
    if (isset($result['Response']['Error'])) {
        return ['success' => false, 'message' => $result['Response']['Error']['Message'] ?? '未知错误'];
    }
    
    if (isset($result['Response']['SendStatusSet']) && count($result['Response']['SendStatusSet']) > 0) {
        $status = $result['Response']['SendStatusSet'][0];
        if ($status['Code'] === 'Ok') {
            return ['success' => true, 'message' => '发送成功'];
        } else {
            return ['success' => false, 'message' => $status['Message'] ?? '发送失败'];
        }
    }
    
    return ['success' => false, 'message' => '响应格式错误'];
}
